package com.lighting.common.log;

import org.slf4j.MDC;

import java.util.Map;

public class MdcRunnable implements Runnable {

    private Map<String, String> mdcContextMap;

    private Runnable runnable;

    public MdcRunnable(Runnable runnable) {
        this.mdcContextMap = MDC.getCopyOfContextMap();
        this.runnable = runnable;
    }

    @Override
    public void run() {
        if (mdcContextMap != null && !mdcContextMap.isEmpty()) {
            MDC.setContextMap(mdcContextMap);
        }
        try {
            runnable.run();
        } finally {
            if (mdcContextMap != null && !mdcContextMap.isEmpty()) {
                MDC.clear();
            }
        }
    }
}